﻿using System;

namespace MathService.DSP.Signals
{
    public static class DigitalSignalExtantions
    {
        public static DigitalSignal Average(this DigitalSignal[] Signals)
        {
            var lv_SignalsCount = Signals.Length;
            var lv_SamplesCount = Signals[0].SamplesCount;
            var x0 = Signals[0].x0;
            var lv_Length = Signals[0].Length;
            var dx = Signals[0].dx;
            for(var i = 1; i < Signals.Length; i++)
            {
                if(x0 != Signals[i].x0)
                    throw new ArgumentException("Сигналы имеют разное время начала");
                if(lv_Length != Signals[i].Length)
                    throw new ArgumentException("Сигналы имеют различную длительность");
                if(dx > Signals[i].dx)
                    dx = Signals[i].dx;
            }

            var lv_Result = new DigitalSignal(dx, x0, lv_Length);

        	for(var i = 0; i < lv_SamplesCount; i++)
            {
                var lv_Sample = .0;
                var lv_x0 = i * dx + x0;
                for(var n = 0; n < lv_SignalsCount; n++) lv_Sample += Signals[n][lv_x0];
                lv_Result[i] = lv_Sample / lv_SignalsCount;
            }
            return lv_Result;
        }
    }
}

